import { FC, useState, useRef, useEffect } from "react";

const Demo: FC = () => {
  const [count, setCount] = useState(0);

  const countRef = useRef(0);

  useEffect(() => {
    countRef.current = count;
  }, [count]);

  // 累加
  function add() {
    setCount(count + 1);
  }

  // 打印count
  function printCount() {
    setTimeout(() => {
      console.log(countRef.current);
    }, 2000);
  }

  return (
    <>
      <p>闭包陷阱</p>
      <div>
        <p>{count}</p>
        <button onClick={add}>累加</button>
        <button onClick={printCount}>打印</button>
      </div>
    </>
  );
};

export default Demo;
